<?php
namespace Admin\Controller;
use Think\Controller;
class MemberController extends BaseController {
	public function month_rentss(){
		$erp_code=I('id');//id即为erp_code
		$User=M('User');
		$user_info=$User->find($erp_code);
		$month_nums=getMonthNum(date("Y-m-d",$user_info['monthrent_time']),date("Y-m-d",time()));

		if($month_nums==0){
			$return['status']=0;
			$return['message']='本月已扣过费用';
			$this->ajaxReturn($return);
		}
		$month_rent=$this->month_rent($erp_code);//企业总仓储费(月租金)
		
		
		$return=$this->out_month_rent($erp_code,$month_rent);//扣月租
		if($return['status']){//增加月租总扣费日志
			$Member=M('Member');
			$Member->where(array('id'=>$user_info['member_id']))->setField('monthrent_time',time());
			$User->where(array('id'=>$erp_code))->setField('monthrent_time',time());//更新时间
			$FeelogD=M('FeelogMonthrent');
			$data_logD['count_price']=$month_rent;//扣费金额
			$data_logD['add_time']=time();
			$data_logD['member_id']=$user_info['member_id'];
			$res_feelogD=$FeelogD->add($data_logD);//更新扣费记录
			if(!$res_feelogD){
				$return['status']=0;
				$return['message']='增加扣费日志失败！';
				$this->ajaxReturn($return);
			}
		}
		$this->ajaxReturn($return);
	}
	//扣月租
	public function out_month_rent($erp_code,$outbound_money){
		$u=M('User');
		$m=M('Member');
		$Feerule=M('Feerule');
		$Feelist=M('Feelist');
		$Feelog=M('Feelog');
		$user_info=$u->where(array('id'=>$erp_code))->find();
		$member_info=$m->where(array('id'=>$user_info['member_id']))->find();

		if($member_info['money']-$member_info['out_money']-$outbound_money>0){//余额大于要扣费金额
			$map_m['id']=$user_info['member_id'];
			$data_member['out_money']=array('exp','out_money+'.$outbound_money);
			$res_member=$m->where($map_m)->save($data_member);

			if($res_member===false){
				$return['status']=0;
				$return['message']='扣费失败！';
				return $return;
			}else{
				$return['status']=1;
				$return['message']='扣费成功！';
				return $return;
			}
		}else{
			$return['status']=0;
			$return['message']='余额不足！';
			return $return;
		}
	}
	//企业总仓储费(月租金)
	public function month_rent($erp_code){
		
		$u=M('User');
		$w=M('Warehouse');
		$uw=M('UserWarehouse');
		$user_info=$u->where(array('id'=>$erp_code))->find();
		$uw_info=$uw->where(array('user_id'=>$erp_code))->find();
		$warehouse_list=explode(',',$uw_info['warehouse_group_id']);
		
		foreach($warehouse_list as $k=>$v){
			$warehouse_info=$w->where(array('id'=>$v))->find();
			
			$fee_count=$this->month_rent_warehouse($erp_code,$warehouse_info['warehouse_cate'],$warehouse_info['warehouse_code']);

			$month_rent+=$fee_count;
			//写入扣费日志明细
			$FeelogD=M('FeelogMonthrentDetail');
			$data_logD['count_price']=$fee_count;//扣费金额
			$data_logD['add_time']=time();
			$data_logD['warehouse_code']=$warehouse_info['warehouse_code'];
			$data_logD['erp_code']=$erp_code;
			$res_feelogD=$FeelogD->add($data_logD);//更新扣费记录
			if(!$res_feelogD){
				$return['status']=0;
				$return['message']='增加扣费日志失败！';
				$this->ajaxReturn($return);
			}
			
			//写入扣费日志
			$Feelog=M('Feelog');

			$data_log['cate_id']=0;//扣费类型id
			$data_log['feecate_id']=7;//费用类型id
			if($warehouse_info['warehouse_cate']==1){
				
				$data_log['feelist_id']=27;//扣费费用名称id
			}
			if($warehouse_info['warehouse_cate']==2){
				$data_log['feecate_id']=27;//费用类型id
				$data_log['feelist_id']=27;//扣费费用名称id
			}
			$data_log['feerule_id']=$user_info['feerule_id'];//费用规则id
			$data_log['count_price']=$fee_count;//扣费总金额
			
			$data_log['out_money_nums']=1;//扣费数量
			$data_log['member_id']=$user_info['member_id'];//扣费的会员id
			$data_log['cate']=1;//1为自动扣费
			$data_log['add_time']=time();
			$res_feelog=$Feelog->add($data_log);//更新扣费记录
			if(!$res_feelog){
				$return['status']=0;
				$return['message']='增加扣费日志失败！';
				$this->ajaxReturn($return);
			}
		
		}
		
		return $month_rent;
	}
	//对应一个仓库的仓储费(月租金)
	//warehouse_cate 1:一般仓 2：跨境（保税）仓
	public function month_rent_warehouse($erp_code,$warehouse_cate,$warehouse_code){
		
		$w=M('Warehouse');
		$w_info=$w->where(array('warehouse_code'=>$warehouse_code))->find();
		$db_name=$w_info['db_name'];
		// dump($db_name);
		$ao=M('ArrivalOrder', C('DB_PREFIX_TT'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $db_name);
		$list=$ao->where(array('erp_code'=>$erp_code))->select();
		
		$month_rent=0;
		// dump($list);
		// die;
		foreach($list as $k=>$v){
			if($warehouse_cate==1){
				$month_rent+=month_rent_normal($v['area'],$v['t_arrival_time'],time());
			}
			if($warehouse_cate==2){
				$month_rent+=month_rent_cross($v['area'],$v['t_arrival_time'],time());
			}
		}
		// dump($month_rent);
		
		return $month_rent;
	}
	public function addmoney(){
		$param = I('param.','','trim');
		$id=$param['id'];
		$count=$param['count'];
		$m=M('Member');
		$data['money']=array('exp','money+'.$count);
		$res=$m->where(array('id'=>$id))->save($data);
		if($res!==false){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}
    public function index(){
        if(I("get.name")!==null && I("get.name")!==''){
            $where['company']=I("get.name");
        }else{
            $where="1=1";
        }
        $user = M('Member');
		$u = M('User');
        $count      = $user->where($where)->count();
        $Page       = new \Think\Page($count,15);
        $show       = $Page->show();
        $list = $user->where($where)->limit($Page->firstRow.','.$Page->listRows)->order("id desc")->select();
		foreach($list as $k=>$v){
			$u_list=$u->where(array('member_id'=>$v['id']))->select();
			foreach($u_list as $ks=>$vs){
				if($ks==0){
					$ids=$vs['id'];
				}else{
					$ids.=','.$vs['id'];
				}
			}
			$list[$k]['ids']=$ids;
		}
		// dump($list);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('count',$count);
        $this->display();
    }

    public function addD($company,$username,$pwd,$pwd2,$email,$warehouse_cate,$warehouse_status){
        if($company==''){
            alert(0,'企业名称不能为空');
        }
        if($username==''){
            alert(0,'用户名不能为空');
        }
        if($pwd==''){
            alert(0,'密码不能为空');
        }
		if($warehouse_status==''){
            alert(0,'仓库属性不能为空');
        }
		if($warehouse_cate==''){
            alert(0,'仓库类型不能为空');
        }
        if($pwd2!=$pwd){
            alert(0,'两次密码不相同');
        }
        if($email==''){
            alert(0,'E-mail不能为空');
        }
        if(!email($email)){
            alert(0,'邮箱地址错误');
        }
        if(!mobile($username)){
            alert(0,'手机号码错误');
        }
        if(M("Member")->where("username='".$username."'")->count()>=1){
            alert(0,'用户名已经存在！');
        }
        if(M("Member")->where("company='".$company."'")->count()>=1){
            alert(0,'公司名称已经存在！');
        }
        if(M("Member")->where("email='".$email."'")->count()>=1){
            alert(0,'电子邮箱已经存在！');
        }
		if($warehouse_status==1){
			$data['wms_has']=1;
		}
        $data['salt']=rand(10000,99999);
        $data['username']=$username;
        $data['company']=$company;
        $data['password']=md5($pwd.$data['salt']);
        // $data['name']=$name;
        $data['email']=$email;
		$data['erp_has']=1;
        // $data['sex']=$sex;
        $data['operator']=session('admin');
        $result=M("Member")->add($data);
		
        if($result){
			$data['member_id']=$result;
			$data['warehouse_code']="T".rand(1000000,9999999);//虚拟仓仓库编码
			$result_user=M("User")->add($data);
            if($result_user){
				//创建erp虚拟仓
				$ACompany=A('Company');
				$reg=A('Company/Reg');
				// dump($reg->createDb(C('DB_PREFIX_T').$username));
				// die;
				if($reg->createDb(C('DB_PREFIX_T').$username)){
					$ACompany->confirm_bind_role_company($result_user,1);//同步对应erp角色权限
					if($warehouse_status==1){//创建物理仓
						$Awarehouse=A('Warehouse');
						$data_warehouse=$company."的仓库";
						$data_warehouse_code=rand(10000000,99999999);
						$data_username=$username;
						$data_pwd=substr(md5($pwd),0,28);
						$data_warehouse_cate=$warehouse_cate;
						$Awarehouse->addD($data_warehouse,$data_warehouse_code,$data_username,$data_pwd,$data_warehouse_cate,$result,1);
						//同步erp物理仓权限到erp系统
						$ACompany->confirm_bind_role_company($result_user,5);//同步对应erp角色权限
					}
				   alert(1,'注册成功');
			    }else{
				   alert(0,'注册失败，请重试');
			    }
			}
        }else{
			M("Member")->where(array('id'=>$result))->setField('erp_has',0);
            alert(0,'添加失败，请重试');
        }
    }

    public function add(){
		$department=M('DepartmentWarehouse');
		$department_list=$department->select();
		
		$this->assign('department_list',$department_list);
        $this->display();
    }
    public function edit($id){
        if($id=='' || !is_numeric($id)){
            alert(0,'操作有误');
        }
        $list=M('Member')->find($id);
        if(!$list){
            alert(0,'操作有误');
        }else{
            $this->assign('list',$list);
            $this->display();
        }
    }
    public function editD($id,$company,$pwd,$pwd2,$email){
        if($company==''){
            alert(0,'公司名称不能为空');
        }
        if($email==''){
            alert(0,'E-mail不能为空');
        }
        // if($name==''){
            // alert(0,'姓名不能为空');
        // }
        if(!email($email)){
            alert(0,'邮箱地址错误');
        }
        if(M("Member")->where("company='".$company."' and id<>'".$id."'")->count()>=1){
            alert(0,'公司名称已经存在！');
        }
        if(M("Member")->where("email='".$email."' and id<>'".$id."'")->count()>=1){
            alert(0,'电子邮箱已经存在！');
        }
        $data['company']=$company;
        if($pwd!=''){
            if($pwd2!=$pwd){
                alert(0,'两次密码不相同');
            }
            $data['salt']=rand(10000,99999);
            $data['password']=md5($pwd.$data['salt']);
        }
        $data['name']=$name;
        $data['email']=$email;
        $data['sex']=$sex;
        $data['operator']=session('admin');
        $result=M("Member")->where(array('id'=>$id))->save($data);
        if($result){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败，请重试');
        }
    }
    public function del($id){
        if($id==''){
            alert(0,'操作有误');
        }
        $group_id=explode('@',$id);
        $i=0;
        foreach($group_id as $id){
            $username=M("Member")->where("id='".$id."'")->getField('username');
            $result= M("Member")->delete(ltrim($id,','));
            $i+=$result*1;
        }
        if(count($group_id)==$i){
            alert(1,'全部删除成功');
        }elseif($i>0){
            alert(1,'删除'.$i."个/共".count($group_id)."个");
        }else{
            alert(0,'删除失败');
        }
    }
	public function examined(){
		$ids=I('ids');
		$map['id']=array('in',$ids);
		$val=I('val');
		$data['status']=$val;
		$res=M('Member')->where($map)->save($data);
		// echo M('Member')->getlastsql();
		if($res!==false){
			alert(1,'成功');
		}else{
			alert(0,'失败');
		}
	}
}